import Cookies from 'js-cookie'
import { setSessionData, getSessionData } from '@/utils/sessionData'

const FAVORITE_KEY = '__favorite__'
const FAVORITE_MAX_LEN = 200

const USED_KEY = '__used__'
const USED_MAX_LEN = 200

const EDIT_KEY = '__edit__'
// const EDIT_MAX_LEN = 200

const USED_MENU = '__menu__'

function insertArray (arr, val, compare, maxLen) {
  const index = arr.findIndex(compare)
  // 将项目放到最前面
  if (index >= 0) {
    arr.splice(index, 1)
  }
  arr.unshift(val)
  if (maxLen && arr.length > maxLen) {
    arr.pop()
  }
}

function deleteFromArray (arr, compare) {
  const index = arr.findIndex(compare)
  if (index > -1) {
    arr.splice(index, 1)
  }
}

export function loadFavorite () {
  const value = Cookies.getJSON(FAVORITE_KEY)
  return value || []
}

export function loadEdit() {
  const value = getSessionData(EDIT_KEY)
  return value || false
}

export function loadMenus() {
  const value = getSessionData(USED_MENU)
  return value || []
}

export function saveFavorite (url) {
  let urls = loadFavorite()
  if (url.hasOwnProperty('num')) { delete url.num }
  insertArray(urls, url, (item) => {
    return item.link === url.link
  }, FAVORITE_MAX_LEN)
  Cookies.set(FAVORITE_KEY, urls)
  return urls
}

export function saveEdit ( status) {
  setSessionData(EDIT_KEY, status)
}

export function saveMenu (data) {
  setSessionData(USED_MENU, data)
}

export function deleteFavorite (url) {
  let urls = loadFavorite()
  deleteFromArray(urls, (item) => {
    return item.link === url.link
  })
  Cookies.set(FAVORITE_KEY, urls)
  return urls
}

export function removeFavorite () {
  Cookies.remove(FAVORITE_KEY)
  return []
}

export function loadUsed () {
  const value = Cookies.getJSON(USED_KEY)
  return value || []
}

export function saveUsed (url) {
  let urls = loadUsed()
  let url_info = Object.assign({}, url)

  if (url_info.hasOwnProperty('num')) {
    url_info.num += 1
  } else {
    url_info.num = 1
    urls.forEach(item => {
      if (item.link === url_info.link && url_info.num) {
        url_info.num = item.num + 1
      }
    })
  }

  insertArray(urls, url_info, (item) => {
    return url_info.link === item.link
  }, USED_MAX_LEN)
  Cookies.set(USED_KEY, urls)
  return urls
}

export function deleteUsed (url) {
  let urls = loadUsed()
  deleteFromArray(urls, (item) => {
    return item.link === url.link
  })
  Cookies.set(USED_KEY, urls)
  return urls
}

export function removeUsed () {
  Cookies.remove(USED_KEY)
  return []
}